//
//  PPAlbumPictureViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/25/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumPictureViewController.h"
#import "PPAlbumPictureDescriptionViewController.h"

#import "PPAlbumPictureActionView.h"

#import "PPAlbumPictureDescriptionView.h"

#import "PPAlbumShareActionView.h"

#import "PPSocializationManager.h"


#import "PPPreViewBar.h"
#define kDescLeftRightMargin 15
#define kDescLinespace 10
#define kMaxSize 140
@interface PPAlbumPictureViewController () <PPAlbumPictureDescriptionViewControllerDelegate, UIScrollViewDelegate,UITextViewDelegate>
@property (readwrite, nonatomic, strong) PPAlbumPictureDescriptionView *descriptionView;
@property (readwrite, nonatomic, assign) NSInteger visibleCount;
@property (readwrite, nonatomic, strong) NSString *albumTitle;
//键盘属性
@property (nonatomic, assign) NSTimeInterval  time;
@property (nonatomic, assign) NSUInteger  curve;
@property (nonatomic, assign) CGFloat  keyboardHeight;

@property (nonatomic,strong) UITextView *textV;
@property (nonatomic,assign) BOOL hiddenKeyBoard;
@property (nonatomic,copy) NSString *desc;
@property (nonatomic,assign) BOOL navigationBarHidden;

@property (nonatomic,assign) BOOL editDesc;


@property (nonatomic,strong) PPPreViewBar *navBarView;

@property (nonatomic,assign) BOOL showKeyboard;
@property (nonatomic,assign) NSInteger currentIndex;
@end

@implementation PPAlbumPictureViewController
- (void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];
    
    self.navBarView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kPPPreViewBarH);
    
}
- (PPPreViewBar *)navBarView{

    if (!_navBarView) {
        _navBarView = [PPPreViewBar preViewBar];
        _navBarView.backgroundColor = WHITE;
        _navBarView.rightBtn.tintColor = COLORA(3, 3, 3);
        WEAKSELF
        _navBarView.BlockDidClick = ^(NSInteger index) {
            if (index == 0) {
                [weakSelf popViewPreviousController];
            }else{
                [weakSelf setupCover];
            }
        };
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 63.5,SCREEN_WIDTH, 0.5)];
        line.backgroundColor = COLORA(240,240, 240);
        [_navBarView addSubview:line];
        
    }
    return _navBarView;
}
- (UITextView *)textV{
    if (!_textV) {
        _textV = [[UITextView alloc] init];
        _textV.font = PPFONTSIZE(kDescFontSize);
        _textV.delegate = self;
        _textV.textContainerInset = UIEdgeInsetsMake(kAlbumDescTopBottomMargin, kAlbumDescLeftRightMargin-kLabelMargin, kAlbumDescTopBottomMargin-5, kAlbumDescLeftRightMargin-kLabelMargin);

        _textV.returnKeyType = UIReturnKeyDone;
        _textV.backgroundColor = COLOR(255, 255, 255, 0.9);
    }
    return _textV;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
//    if (iOS7Later) [UIApplication sharedApplication].statusBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
//    if (iOS7Later) [UIApplication sharedApplication].statusBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.navBarView];
    
    [self setupBackItem];
    
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;
    

//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-home-more"] style:UIBarButtonItemStylePlain target:self action:@selector(moreItemDidPressed)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设为封面" style:UIBarButtonItemStylePlain target:self action:@selector(setupCover)];
    [self.navigationItem.rightBarButtonItem setTintColor:NAV_RightItemColor];
    

    
    
    if (IS_IOS_8) {
            [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16)} forState:UIControlStateNormal];
    }else{
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    
    
    
    _descriptionView = [[PPAlbumPictureDescriptionView alloc] init];
    [self.view addSubview:_descriptionView];

    self.view.backgroundColor = WHITE;
    [_descriptionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];

    _descriptionView.backgroundColor = CLEAR;
    
    [self updateRelevantInfos];
    
    [self.view addSubview:self.textV];

    [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
//        make.height.mas_equalTo(@([self heightForString:self.textV andWidth:self.view.width - kAlbumDescLeftRightMargin*2]));
    }];
    
    self.descriptionView.label.hidden = YES;
    
    //keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWasShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];

    
    if (self.textV.text.length > 0) {
        [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo([self heightForString:self.textV andWidth:SCREEN_WIDTH - 20]);
        }];
        
        // 更新约束
        [UIView animateWithDuration:self.time animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}

///MARK: 设置封面
- (void)setupCover{

    [MobClick event:@"45"];
    
    PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.index];
    
    PPAlbumImageModel *image = [PPAlbumImageModel find:@{@"uuid": artwork.uuid}];
    
    [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:self.auuid insertedArtworks:nil modifiedArtworks:nil deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:image.uuid];
    
    [self.navigationController.view toastMessage:@"设置成功"];
}
#pragma mark - textViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView{
    self.editDesc = NO;
//    _textV.backgroundColor = COLOR(255, 255, 255, 0.9);
    CGFloat h = [self heightForString:self.textV andWidth:self.view.width - kAlbumDescLeftRightMargin*2];
    
    
    if (h < 33.5) {
        h = 33.5;
    }
    
    [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(h);
    }];
 
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    
//    _textV.backgroundColor = COLOR(255, 255, 255, 0.9);
//    _textV.textContainerInset = UIEdgeInsetsMake(15, 10,15, 10);
    
 
    
    if (self.editDesc) {
        self.index = self.currentIndex;
        [self updateDesc:textView.text];
        
    }else{
        [self descTextViewText:_descriptionView.desc];
        
    }   
}

- (void)descTextViewText:(NSString *)text{
    NSString *desc = text;
    
    if (self.showKeyBoard) {
        desc = self.textV.text;
        self.textV.textContainerInset = UIEdgeInsetsMake(kAlbumDescTopBottomMargin, kAlbumDescLeftRightMargin-kLabelMargin, kAlbumDescTopBottomMargin-5, kAlbumDescLeftRightMargin-kLabelMargin);
        NSDictionary *attributes;
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        
        paragraphStyle.lineSpacing = kDescLinespace/2 + 1;
        if (desc.length <= 0) {
            desc = @"添加描述";
            attributes = @{NSFontAttributeName:PPFONTSIZE(kDescFontSize),NSForegroundColorAttributeName:[UIColor grayColor],
                           NSParagraphStyleAttributeName:paragraphStyle};
        }else{
            attributes = @{NSFontAttributeName:PPFONTSIZE(kDescFontSize),NSForegroundColorAttributeName:[UIColor blackColor],
                           NSParagraphStyleAttributeName:paragraphStyle};
            
        }
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:desc attributes:attributes];
        
        self.textV.attributedText = string;
        
        [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@([self heightForString:self.textV andWidth:self.view.width]));
        }];
        
        // 更新约束
        [UIView animateWithDuration:self.time animations:^{
            [self.view layoutIfNeeded];
        }];

        return;
    }
    
    NSDictionary *attributes;
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    paragraphStyle.lineSpacing = kDescLinespace/2 + 1;
    if (desc.length <= 0) {
        desc = @"添加描述";
         attributes = @{NSFontAttributeName:PPFONTSIZE(kDescFontSize),NSForegroundColorAttributeName:[UIColor grayColor],
                        NSParagraphStyleAttributeName:paragraphStyle};
    }else{
        attributes = @{NSFontAttributeName:PPFONTSIZE(kDescFontSize),NSForegroundColorAttributeName:[UIColor blackColor],
                       NSParagraphStyleAttributeName:paragraphStyle};
        
    }
    
    NSInteger index = desc.length;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:desc attributes:attributes];
    
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
    textAttachment.image = [UIImage imageNamed:@"icon_pen"];
    textAttachment.bounds = CGRectMake(0, -2.5, textAttachment.image.size.width*0.40, textAttachment.image.size.height*0.40);
    NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [string insertAttributedString:textAttachmentString atIndex:index];//index为用户指定要插入图片的位置
    
    self.textV.attributedText = string;
    
    
    
    [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@([self heightForString:self.textV andWidth:self.view.width]));
    }];

    // 更新约束
    [UIView animateWithDuration:self.time animations:^{
        [self.view layoutIfNeeded];
    }];
}
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}
- (void)textViewDidChange:(UITextView *)textView{

    textView.font = PPFONTSIZE(kDescFontSize);

    if (textView.text.charCount > kMaxSize) {
            [self.navigationController.view toastMessage:[NSString stringWithFormat:@"最多%zd字",kMaxSize]];
    }
    
//    NSString *desc = textView.text.length>0?textView.text:@"";
//
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    if (desc.length > 0) {
//        paragraphStyle.lineSpacing = kDescLinespace-kLabelMargin;
//    }
//    
//    NSDictionary *attributes = @{NSFontAttributeName:PPFONTSIZE(15),NSForegroundColorAttributeName:[UIColor blackColor],
//                                 NSParagraphStyleAttributeName:paragraphStyle};
//    
//    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:desc attributes:attributes];
//    self.textV.attributedText = string;
//
    
//

    [textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo([self heightForString:textView andWidth:SCREEN_WIDTH - 20]);
    }];
    
    // 更新约束
    [UIView animateWithDuration:self.time animations:^{
        [self.view layoutIfNeeded];
    }];
}
//MARK:键盘
- (void)keyBoardWasShow:(NSNotification *)notice{
    self.hiddenKeyBoard = YES;
    if (_descriptionView.desc.length <= 0) {
//        self.textV.text = nil;
        self.textV.textColor = BLACK;
    }else{
//        self.textV.text = _descriptionView.desc;
    }
    
    NSDictionary *dict=notice.userInfo;
    self.time = [dict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    self.curve = [dict[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    self.keyboardHeight = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//    self.textV.font = PPFONTSIZE(15);
    
    if (self.showKeyBoard == NO) {
        NSString *desc = _descriptionView.desc.length>0?_descriptionView.desc:@"";
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        if (desc.length > 0) {
            paragraphStyle.lineSpacing = kDescLinespace-kLabelMargin;
        }
        
        NSDictionary *attributes = @{NSFontAttributeName:PPFONTSIZE(kDescFontSize),NSForegroundColorAttributeName:[UIColor blackColor],
                                     NSParagraphStyleAttributeName:paragraphStyle};
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:desc attributes:attributes];
        self.textV.attributedText = string;
        
        [self.textV mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@([self heightForString:self.textV andWidth:self.view.width]));
        }];
    }
    
    
    
    [UIView animateWithDuration:self.time animations:^{
        [UIView setAnimationCurve:self.curve];
        self.textV.transform=CGAffineTransformMakeTranslation(0,-self.keyboardHeight);
    }];
    
    self.showKeyBoard = YES;
}
- (void)keyboardWillBeHidden:(NSNotification *)notice{
    self.hiddenKeyBoard = NO;
    self.showKeyBoard = NO;

    [UIView animateWithDuration:self.time animations:^{
        //曲线
        [UIView setAnimationCurve:self.curve];
        self.textV.transform=CGAffineTransformIdentity;
        
    }];
}
- (void)setAuuid:(NSString *)auuid {
    _auuid = auuid;

    if(auuid == nil) {
        return;
    }

    PPAlbumModel *album = [PPAlbumModel find:@{@"auuid" : auuid}];
    _albumTitle = album.title;
    _visibleCount = [PPAlbumImageModel countWhere:@{@"auuid" : auuid, @"deleted" : @(NO)}];

}
- (void)showDesc{
    self.textV.textContainerInset = UIEdgeInsetsMake(kAlbumDescTopBottomMargin, kAlbumDescLeftRightMargin-kLabelMargin, kAlbumDescTopBottomMargin-5, kAlbumDescLeftRightMargin-kLabelMargin);
    
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] init];
        
        NSAttributedString *albumTitle = [[NSAttributedString alloc] initWithString:_albumTitle attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:15], NSForegroundColorAttributeName : [UIColor blackColor]}];
        [title appendAttributedString:albumTitle];
        
        NSAttributedString *linebreak = [[NSAttributedString alloc] initWithString:@"\r\n"];
        [title appendAttributedString:linebreak];
        
        NSAttributedString *indexTitle = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%zd/%zd", self.currentIndex + 1, _visibleCount] attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor blackColor]}];
        [title appendAttributedString:indexTitle];
        self.navBarView.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.navBarView.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        
        if (IS_IPHONE_6 && _albumTitle.length > 12) {
            _albumTitle = [NSString stringWithFormat:@"%@...",[_albumTitle substringWithRange:NSMakeRange(0, 12)]];
            
        }
        
        self.navBarView.titleLabel.text = _albumTitle;
        self.navBarView.pageLabel.text = [NSString stringWithFormat:@"%zd/%zd", self.currentIndex + 1, _visibleCount];
        
        
        PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.currentIndex];
        
        PPAlbumImageModel *image = [PPAlbumImageModel find:@{@"uuid": artwork.uuid}];
        
        _descriptionView.desc = image.desc;
        
        
        self.desc = image.desc;
        
        [self descTextViewText:_descriptionView.desc];
        
    
}
- (void)updateRelevantInfos {

    if (_albumTitle.length > 0 && self.showKeyBoard) {
       
        [self showDesc];
        
        return;
    }

    
    if(_albumTitle.length > 0) {
        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] init];

        NSAttributedString *albumTitle = [[NSAttributedString alloc] initWithString:_albumTitle attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:15], NSForegroundColorAttributeName : [UIColor blackColor]}];
        [title appendAttributedString:albumTitle];

        NSAttributedString *linebreak = [[NSAttributedString alloc] initWithString:@"\r\n"];
        [title appendAttributedString:linebreak];

        NSAttributedString *indexTitle = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%zd/%zd", self.index + 1, _visibleCount] attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor blackColor]}];
        [title appendAttributedString:indexTitle];

//        UILabel *titleLabel = [[UILabel alloc] init];
//        titleLabel.numberOfLines = 0;
//        titleLabel.textAlignment = NSTextAlignmentCenter;
//        titleLabel.attributedText = title;
//        [titleLabel sizeToFit];
        
//        self.navigationItem.titleView = titleLabel;
//        self.navBarView.titleLabel.numberOfLines = 0;
//         self.navBarView.titleLabel.attributedText = title;
        self.navBarView.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.navBarView.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        
        if (IS_IPHONE_6 && _albumTitle.length > 12) {
            _albumTitle = [NSString stringWithFormat:@"%@...",[_albumTitle substringWithRange:NSMakeRange(0, 12)]];
            
        }
        
        self.navBarView.titleLabel.text = _albumTitle;
        self.navBarView.pageLabel.text = [NSString stringWithFormat:@"%zd/%zd", self.index + 1, _visibleCount];
        
    }

    PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.index];

    PPAlbumImageModel *image = [PPAlbumImageModel find:@{@"uuid": artwork.uuid}];

    _descriptionView.desc = image.desc;
    

    self.desc = image.desc;
    self.currentIndex = self.index;
    [self descTextViewText:_descriptionView.desc];
}

- (void)moreItemDidPressed {

    [MobClick event:@"43"];
    PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.index];

    PPAlbumImageModel *image = [PPAlbumImageModel find:@{@"uuid": artwork.uuid}];

    PPAlbumPictureActionView *actionView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumPictureActionView" owner:nil options:nil].firstObject;
    actionView.frame = CGRectMake(0, self.navigationController.view.height - actionView.height, self.navigationController.view.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.navigationController.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(self)weakSelf = self;
    __weak typeof(popoverView)weakPopover = popoverView;
    [actionView.cancelButton setActionBlock:^(UIControl *control) {
        [MobClick event:@"48"];
        [weakPopover dismissAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.coverButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{

            [MobClick event:@"45"];
            [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:weakSelf.auuid insertedArtworks:nil modifiedArtworks:nil deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:image.uuid];

            [weakSelf.navigationController.view toastMessage:@"设置成功"];

        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.shareButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"47"];
            [weakSelf didSelectShareImage:image];

        }];
    } forControlEvents:UIControlEventTouchUpInside];

    if(artwork.image == nil && artwork.URLString.length == 0) {
        actionView.saveButton.enabled = NO;
    } else {
        actionView.saveButton.enabled = YES;

        [actionView.saveButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.navigationController.view animated:YES];

                [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:artwork.URLString] options:kNilOptions progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {

                    dispatch_async(dispatch_get_main_queue(), ^{

                        [hud hide:YES];

                        if(error == nil) {
                            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                        } else {
                            [weakSelf.navigationController.view toastMessage:error.networkPrompt];
                        }
                    });
                }];
                //                }
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [actionView.deleteButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"46"];
            UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:nil message:@"确定删除图片？" preferredStyle:UIAlertControllerStyleAlert];
            [alertControler addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

            }]];
            [alertControler addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:weakSelf.auuid insertedArtworks:nil modifiedArtworks:nil deletedArtworks:@[artwork] tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }]];
            [weakSelf presentViewController:alertControler animated:YES completion:nil];
        }];
    } forControlEvents:UIControlEventTouchUpInside];

    [actionView.descButton setActionBlock:^(UIControl *control) {
        [weakPopover dismissAnimated:YES completion:^{
            [MobClick event:@"44"];
            __strong typeof(weakSelf)strongSelf = weakSelf;

            if(strongSelf == nil) {
                return;
            }

            PPAlbumPictureDescriptionViewController *descriptionViewController = [[PPAlbumPictureDescriptionViewController alloc] init];
            descriptionViewController.delegate = strongSelf;
            descriptionViewController.artwork = artwork;
            [weakSelf.navigationController pushViewController:descriptionViewController animated:YES];

        }];
    } forControlEvents:UIControlEventTouchUpInside];


    [popoverView displayAnimated:YES completion:nil];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error) {
        if([[error domain] isEqualToString:ALAssetsLibraryErrorDomain] && [error code] == ALAssetsLibraryDataUnavailableError) {
            [self.navigationController.view toastMessage:@"图片保存失败"];
        }
    } else {
        [self.navigationController.view toastMessage:@"图片保存成功"];
    }
}

- (void)didSelectShareImage:(PPAlbumImageModel *)image {

    PPAlbumModel *album = [PPAlbumModel find:@{@"auuid": image.auuid}];

    __block NSError *error_ = nil;
    __block NSString *title = @"美图精彩推荐";
    __block NSString *subtitle = [NSString stringWithFormat:@"我在PickPic的相册《%@》发现一张好照片，推荐给你！", album.title];
    __block UIImage *image_ = nil;


    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    dispatch_group_t group = dispatch_group_create();

    if(image.URLString.length > 0) {
        dispatch_group_enter(group);

        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:image.URLString] options:kNilOptions progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            if(error == nil) {
                image_ = image;
            } else {
                error_ = error;
            }

            dispatch_group_leave(group);
        }];
    } else {
        image_ = image.artwork.image;
    }

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        [hud hide:YES];

        if(error_ != nil) {
            [self.navigationController.view toastMessage:error_.networkPrompt];
        } else {
            [self sharePictureWithTitle:title subtitle:subtitle url:nil image:image_];
        }
    });
}

- (void)sharePictureWithTitle:(NSString *)title subtitle:(NSString *)subtitle url:(NSString *)url image:(UIImage *)image {

    UIView *actionView = nil;

    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin] && [[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:4];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:5];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:6];
    } else {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:7];
    }

    actionView.frame = CGRectMake(0, self.view.height - actionView.height, self.view.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:self.view contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleDimmed];

    __weak typeof(popoverView)weakPopover = popoverView;

    if([actionView respondsToSelector:@selector(wechatButton)]) {
        UIButton *wechatButton = [actionView valueForKey:@"wechatButton"];
        [wechatButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeixinChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(circleButton)]) {
        UIButton *circleButton = [actionView valueForKey:@"circleButton"];
        [circleButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeixinCircle];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(weiboButton)]) {
        UIButton *weiboButton = [actionView valueForKey:@"weiboButton"];
        [weiboButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeWeibo];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(qqButton)]) {
        UIButton *qqButton = [actionView valueForKey:@"qqButton"];
        [qqButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image type:PPSocializationShareTypeQQChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(cancelButton)]) {
        UIButton *cancelButton = [actionView valueForKey:@"cancelButton"];
        [cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [popoverView displayAnimated:YES completion:nil];
}


- (void)didEndScrolling {
    [super didEndScrolling];

    if (!self.showKeyBoard) {
        
        [self updateRelevantInfos];
    }
    
}
- (void)willBeginScrolling{

    if (self.hiddenKeyBoard) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
    }
}
- (BOOL)scrollsOnScrolling {
    
    if (self.hiddenKeyBoard) {
        return NO;
    }
    
    return NO;
}

#pragma mark - PPAlbumPictureDescriptionViewControllerDelegate
///MARK: 更新描述
- (void)updateDesc:(NSString *)changeDesc{

    
    PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.currentIndex];
    artwork.desc = changeDesc;
    artwork.modified = @(YES);
    
    [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_auuid insertedArtworks:nil modifiedArtworks:@[artwork] deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];
   
    [self updateRelevantInfos];
}
- (void)descriptionViewController:(PPAlbumPictureDescriptionViewController *)descriptionViewController didSaveDescription:(NSString *)description {
    PPAbstractArtwork *artwork = descriptionViewController.artwork;
    artwork.desc = description;
    artwork.modified = @(YES);

    [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:_auuid insertedArtworks:nil modifiedArtworks:@[artwork] deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:nil];

    [self updateRelevantInfos];
}

- (void)pictureViewCell:(PPAbstractPictureViewCell *)pictureViewCell didRecognizedSingleTapGesture:(UITapGestureRecognizer *)gesture{

    if (self.hiddenKeyBoard) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        return ;
    }
    
     _navigationBarHidden = !_navigationBarHidden;
    if(_navigationBarHidden) {
        self.textV.hidden = YES;
        _descriptionView.label.hidden = NO;
        _descriptionView.desc = self.desc;
        self.view.backgroundColor = BLACK;
        _descriptionView.backgroundColor = COLOR(0, 0, 0, 0.5);
        self.navBarView.hidden = YES;
        
//        _descriptionView.backgroundColor = [UIColor orangeColor];
//        _descriptionView.label.backgroundColor = BLUE;
        
        [self dismissNavigationBarAnimated:YES completion:nil];
    } else {
        self.textV.hidden = NO;
        _descriptionView.label.hidden = YES;
        self.view.backgroundColor = WHITE;
        _descriptionView.backgroundColor = CLEAR;
        self.navBarView.hidden = NO;
        
        
//        self.textV.backgroundColor = RED;
        [self displayNavigationBarAnimated:YES completion:nil];
    }
}

- (void)pictureViewCell:(PPAbstractPictureViewCell *)pictureViewCell didRecognizedLongPressGesture:(UILongPressGestureRecognizer *)gesture{

    if (self.hiddenKeyBoard) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        return ;
    }
    
    UIAlertController *alertview=[UIAlertController alertControllerWithTitle:@"" message:@"保存到本地相册" preferredStyle:UIAlertControllerStyleActionSheet];
    // 设置按钮
    UIAlertAction *cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *defult = [UIAlertAction actionWithTitle:@"保存原图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        PPAbstractArtwork *artwork = [self.artworks safeObjectAtIndex:self.index];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:artwork.URLString] options:kNilOptions progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hide:YES];
                
                if(error == nil) {
                    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                } else {
                    [self.navigationController.view toastMessage:error.networkPrompt];
                }
            });
        }];

    }];
    
    [alertview addAction:cancel];
    [alertview addAction:defult];
    [self presentViewController:alertview animated:YES completion:nil];
    
}
#pragma mark -编辑描述 完成
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
//        if (textView.text.length <=80) {
        if(textView.text.charCount <= kMaxSize){
            self.editDesc = YES;
        }

        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        
        return NO;
    }
    
    
    return YES;
}
@end
